package cn.gjxblog.mq.mechanism.qos;

import cn.gjxblog.mq.utils.ConnectionUtils;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.QueueingConsumer;

/**
 * @author gjx
 * @version v1.0
 * @Description 实现限流 必须 autoAck=false
 * @date 2019/7/4 11:48
 */
public class Consumer {
    public static void main(String[] args) throws Exception {
        Connection connection = ConnectionUtils.getConnection();

        Channel channel = connection.createChannel();

        //1 限流
        channel.basicQos(0,3,false);

        String exchangeName = "test_qos_exchange";
        String routingKey = "qos.#";
        String queueName = "test_qos_queue";
        channel.exchangeDeclare(exchangeName,"topic",true);
        channel.queueDeclare(queueName,true,false,false,null);
        channel.queueBind(queueName,exchangeName,routingKey);

        QueueingConsumer queueingConsumer = new QueueingConsumer(channel);

        channel.basicConsume(queueName,false,queueingConsumer);
        while (true) {
            QueueingConsumer.Delivery deliver = queueingConsumer.nextDelivery();
            String msg = new String(deliver.getBody());
            System.out.println("msg is: " + msg);

            channel.basicAck(deliver.getEnvelope().getDeliveryTag(),false);
        }

    }
}
